package com.spdzen.support.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.spdzen.support.JsonUtils;
import com.spdzen.support.RequestInfo;
import com.spdzen.support.RequestUtils;
import com.spdzen.support.WebContextUtils;

/**
 * 通用的请求拦截器，记录每次请求的情况
 * @author accountwcx@qq.com
 *
 */
public class RequestInfoInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		RequestInfo info = new RequestInfo();
		info.setClientIp(RequestUtils.getClientIp(request));

		Map<String, String[]> params = request.getParameterMap();
		if (params != null && params.size() > 0) {
			info.setParameters(JsonUtils.toJSONString(params));
		}

		info.setServletPath(request.getServletPath());
		info.setUserAgent(RequestUtils.getUserAgent(request));
		info.setStart(System.currentTimeMillis());
		info.setWeixinBrowser(RequestUtils.isWeixinBrowser(request));

		if (handler != null && HandlerMethod.class.isAssignableFrom(handler.getClass())) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			String clazz = handlerMethod.getMethod().getDeclaringClass().getName();
			String method = handlerMethod.getMethod().toString();
			info.setClazz(clazz);
			info.setMethod(method.replaceAll(clazz + ".", ""));
		}
		
		WebContextUtils.setRequestInfo(info, request);

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		RequestInfo info = WebContextUtils.getRequestInfo(request);
		info.setDuration(System.currentTimeMillis() - info.getStart());
		info.setResponseStatus(response.getStatus());

		if (ex != null) {
			info.addException(ExceptionUtils.getStackTrace(ex));
		}
		
		//LogUtils.logRequest(info);
	}
}
